'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''
from dopplershift.core.exc import DSException
import os

class ConfigNotFound(DSException):
    '''
    Config file not found
    '''
class ConfigWithErrors(DSException):
    '''
    Config file contain errors
    '''

class PrototypeConfig:
    def __init__(self, resource):
        '''
        
        '''
    def _fetchContent(self, resource):
        '''
        Read data from resource and return readed and prepared conf structure
        '''
        
class FileBasedConfig(PrototypeConfig):
    def __init__(self, resource):
        self._content = self._fetchContent(resource)
    def _fetchContent(self, filename):
        import os
        if not os.path.isfile(filename):
            raise ConfigNotFound(filename)
        fh = open(filename)
        content = fh.read()
        fh.close()
        return content
class XMLFileBasedConfig(FileBasedConfig):
    _root_loaded = False
    def __init__(self, resource):
        FileBasedConfig.__init__(self, resource)
    def _loadFile(self, filename):
        from lxml import etree
        parser = etree.XMLParser(encoding='utf-8', remove_blank_text=True, remove_comments=True, strip_cdata=False)
        content = etree.parse(filename, parser)
        return content
    def _fetchContent(self, filename):
        root = self._loadFile(filename)
        self._fetchIncludes(root, os.path.dirname(filename))
        return root
    def _fetchIncludes(self, root, root_path):
        root = root.getroot()
        for el in root.xpath('/*/include/@path'):
            content = self._fetchContent(os.path.join(root_path, el))
            root.append(content.getroot())
            
        